#include "main.h"
// 要求将所有代码写在本文件内

typedef struct delete delete;

int ListInitiate(SLNode **head)/*初始化*/ {
    *head = (SLNode*) malloc(sizeof(SLNode));
    if(!*head){
        return 1;
    }
    (*head)->next = NULL;
  return 0;
}

int ListLength(SLNode *head) /* 单链表的长度*/{
   SLNode *p;
   p=head->next;
   int i=0;
   while(p){
       i++;
       p=p->next;
   }
  return i;
}

int ListInsert(SLNode *head, int i, DataType x) {
    SLNode *p=head,*s;int j=-1;
    while(p&&j<i-1){p=p->next;++j;}
    if(!p||j>i) return 1;
    s= (SLNode*) malloc(sizeof(SLNode));
    s->data = x;

    s->next=p->next;
    p->next=s;

  return 0;
}

int ListDelete(SLNode *head, int i, DataType *x) {
    SLNode *p=head;int j=-1;
    while(p->next&&j<i-1){
        p=p->next;++j;
    }
    if(!(p->next)||j>i-1) return 1;
    SLNode *q=p->next;
    p->next=q->next;
    *x=q->data;
    free(q);
    return 0;
}

int ListGet(SLNode *head, int i, DataType *x) {
    SLNode *p;
    p=head->next;int j=0;
    while(p&&j<i){
        p=p->next;++j;
    }
    if(!p||j>i) return 1;
    *x=p->data;
    return 0;
}

int Destroy(SLNode **head)
{
    SLNode *p,*r;
    p=*head;
    while(p!=NULL)
    {
        r=p;
        p=p->next;
        free(r);
    }
    *head=NULL;
    return 0;
}

void main(void) {
  SLNode *head;
  int i , x;
  ListInitiate(&head);/*初始化*/
  for(i = 0; i < 10; i++) {
    if(ListInsert(head, i, i+1) == 1) /*插入10个数据元素*/
      {
        printf("错误1! \n");
        return;
      }
  }

  if(ListDelete(head, 4, &x) == 1) { /*删除数据元素5*/
    printf("错误2! \n");
    return;
  }
  printf("%d\n", ListLength(head));

  for(i = 0; i < ListLength(head); i++) {
    if(ListGet(head, i, &x) == 1) /*取元素*/
      {
        printf("错误!3 \n");
        return;
      }
    else printf("%d     ", x);/*显示数据元素*/
  }

  Destroy(&head);
}
